package com.practice.xml.xstream;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

import com.practice.xml.Company;
import com.practice.xml.CompanyDefinition;
import com.practice.xml.Employee;
import com.practice.xml.EmployeeDefinition;
import com.practice.xml.XmlProcessor;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.QNameMap;
import com.thoughtworks.xstream.io.xml.StaxDriver;

public class XstreamXmlProcessor implements XmlProcessor {

	private XStream xStream;
	
	public XstreamXmlProcessor() {
		//QNameMap qNameMap = new QNameMap();
		//qNameMap.setDefaultNamespace("");
		//qNameMap.setDefaultPrefix("");
		//StaxDriver staxDriver = new StaxDriver(qNameMap);
		xStream = new XStream();
		xStream.autodetectAnnotations(true);
		
		xStream.alias(CompanyDefinition.NAME, Company.class);
		xStream.aliasField(CompanyDefinition.ATTRIBUTE_NAME, Company.class, "name");
		xStream.aliasField(CompanyDefinition.ELEMENT_EMPLOYEES, Company.class, "employees");
		xStream.alias(EmployeeDefinition.NAME, Employee.class);
		xStream.aliasField(EmployeeDefinition.ELEMENT_NAME, Employee.class, "name");
		xStream.aliasField(EmployeeDefinition.ELEMENT_SEX, Employee.class, "sex");
		xStream.aliasField(EmployeeDefinition.ELEMENT_AGE, Employee.class, "age");
	}
	
	@Override
	public void createXml(Company company, String filePath) {
		
		System.out.println(xStream.toXML(company));
		
		Writer fileWriter = null;
		try {
			fileWriter = new FileWriter(filePath);
			xStream.toXML(company, fileWriter);
		} catch (IOException ex) {
			System.out.println(ex.getMessage());
			System.out.println(ex.getStackTrace());			
		} finally {
			if (fileWriter != null) {
				try {
					fileWriter.close();
				} catch (IOException ex) {
					System.out.println(ex.getMessage());
					System.out.println(ex.getStackTrace());					
				}
			}
		}
	}

	@Override
	public Company parseXml(String filePath) {
		Reader fileReader = null;
		Company company = null;
		try {
			fileReader = new FileReader(filePath);
			company = (Company) xStream.fromXML(fileReader);
		} catch (FileNotFoundException ex) {
			System.out.println(ex.getMessage());
			System.out.println(ex.getStackTrace());				
		} finally {
			if (fileReader != null) {
				try {
					fileReader.close();
				} catch (IOException ex) {
					System.out.println(ex.getMessage());
					System.out.println(ex.getStackTrace());	
				}
			}
		}
		return company;
	}

}